'use client';

import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { updateUserStatusInfo } from '@/services/api';
import type { TBody } from '@/types';
import type {
  IDifference,
  IUpdateUserStatusInfoBody,
  IUser,
} from '@/interfaces';
import diff from 'microdiff';
import useToast from '@/hooks/useToast';
import { getDiffData, getFilterData, isEmpty } from '@/lib/tool';

export default function UpdateUserState({ details }: { details: IUser }) {
  const [form, setForm] = useState<{
    accountNonExpired?: boolean;
    credentialsNonExpired?: boolean;
    accountNonLocked?: boolean;
    enabled?: boolean;
  }>({
    accountNonExpired: true,
    credentialsNonExpired: true,
    accountNonLocked: true,
    enabled: true,
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const { show } = useToast();

  const updateUserStatusInfoMutation = useMutation(
    async (variables: TBody<IUpdateUserStatusInfoBody>) => {
      await updateUserStatusInfo(variables);
    },
  );

  useEffect(() => {
    if (details) {
      setForm({
        accountNonExpired: details.accountNonExpired,
        credentialsNonExpired: details.credentialsNonExpired,
        accountNonLocked: details.accountNonLocked,
        enabled: details.enabled,
      });
    }
  }, [details]);
  useEffect(() => {
    if (details) {
      const differences = diff(
        {
          accountNonExpired: details.accountNonExpired,
          credentialsNonExpired: details.credentialsNonExpired,
          accountNonLocked: details.accountNonLocked,
          enabled: details.enabled,
        },
        form,
      );
      setDifferenceData(differences);
    }
  }, [form, details]);

  function onChangeForm(e: ChangeEvent<HTMLInputElement>) {
    const name = e.target.name;
    const value = e.target.checked;
    setForm({ ...form, [name]: value });
  }

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const body = getFilterData(getDiffData(differenceData));
      if (isEmpty(body)) {
        show({
          type: 'SUCCESS',
          message: '保存完成',
        });
        return;
      }

      await updateUserStatusInfoMutation.mutateAsync({
        id: details.id,
        data: body,
      });

      clearData();
      show({
        type: 'SUCCESS',
        message: '保存完成',
      });
    } catch (e) {
      updateUserStatusInfoMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function clearData() {
    setDifferenceData([]);
  }

  return (
    <div className="row">
      <div className="col">
        <form onSubmit={onClickSave} className="vstack gap-4">
          <div className="form-control vstack gap-4">
            <div className="form-check form-switch">
              <input
                className="form-check-input"
                type="checkbox"
                role="switch"
                id="yw-admin-user-state-accountNonExpired"
                name="accountNonExpired"
                checked={form.accountNonExpired}
                onChange={onChangeForm}
              />
              <label
                className="form-check-label"
                htmlFor="yw-admin-user-state-accountNonExpired"
              >
                帐户未过期
              </label>
            </div>
            <div className="form-check form-switch">
              <input
                className="form-check-input"
                type="checkbox"
                role="switch"
                id="yw-admin-user-state-accountNonLocked"
                name="accountNonLocked"
                checked={form.accountNonLocked}
                onChange={onChangeForm}
              />
              <label
                className="form-check-label"
                htmlFor="yw-admin-user-state-accountNonLocked"
              >
                凭证未过期
              </label>
            </div>
            <div className="form-check form-switch">
              <input
                className="form-check-input"
                type="checkbox"
                role="switch"
                id="yw-admin-user-state-credentialsNonExpired"
                name="credentialsNonExpired"
                checked={form.credentialsNonExpired}
                onChange={onChangeForm}
              />
              <label
                className="form-check-label"
                htmlFor="yw-admin-user-state-credentialsNonExpired"
              >
                帐户未锁定
              </label>
            </div>
            <div className="form-check form-switch">
              <input
                className="form-check-input"
                type="checkbox"
                role="switch"
                id="yw-admin-user-state-enabled"
                name="enabled"
                checked={form.enabled}
                onChange={onChangeForm}
              />
              <label
                className="form-check-label"
                htmlFor="yw-admin-user-state-enabled"
              >
                账号未禁用
              </label>
            </div>
          </div>

          <button
            type="submit"
            disabled={updateUserStatusInfoMutation.isLoading}
            className="btn btn-success w-25 my-4"
          >
            {updateUserStatusInfoMutation.isLoading && (
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
            )}
            更新
          </button>
        </form>
      </div>
    </div>
  );
}
